package com.mrlv.rabbitmq;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author Mrlv
 * @version 1.0
 * @description:
 * 分支合并框架 - 递归
 *
 * ForkJoinPool
 * ForkJoinTask
 * RecursiveTask
 *
 * @date 2021年11月19日 17:51
 */
public class ForkJoinDemo {


    public static void main(String[] args) throws ExecutionException, InterruptedException {

        MyTask myTask = new MyTask(0, 100);

        ForkJoinPool forkJoinPool = new ForkJoinPool();

        ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);

        System.out.println(forkJoinTask.get());

        forkJoinPool.shutdown();
    }
}

class MyTask extends RecursiveTask<Integer> {

    private static final Integer ADJUST_VALUE = 10;

    private int begin;

    private int end;

    private int result;

    public MyTask(int begin, int end) {

        this.begin = begin;

        this.end = end;
    }

    @Override
    protected Integer compute() {
        if ((end - begin) <= this.ADJUST_VALUE) {
            for (int i = begin; i <= end; i++) {
                result = result + i;
            }
        } else {
            int middle = (end + begin) / 2;
            MyTask leftTask = new MyTask(begin, middle);
            leftTask.fork();

            MyTask rightTask = new MyTask(middle + 1, end);
            rightTask.fork();

            result = leftTask.join() + rightTask.join();
        }
        return result;
    }
}